package com.py.user.service.impl;

import com.py.common.redis.CacheService;
import com.py.model.common.dtos.ResponseResult;
import com.py.model.common.enums.AppHttpCodeEnum;
import com.py.model.user.dtos.UserRelatioinDto;
import com.py.user.service.ApUserFollowBehaviorService;
import com.py.utils.common.ApUserThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @ClassName ApUserFollowBehaviorServiceImpl
 * @Description TODO
 * @Author AXing
 * @Date 2022/11/17 11:24
 * @Version 1.0
 */
@Service
@Slf4j
public class ApUserFollowBehaviorServiceImpl implements ApUserFollowBehaviorService {
    @Autowired
    private CacheService cacheService;
    /**
     * 用户关注
     * @param dto
     * @return
     */
    @Override
    public ResponseResult userFollow(UserRelatioinDto dto) {


        //获取用户id
        Integer userId = ApUserThreadLocalUtil.get().getId();
        String followKey = dto.getAuthorId() + "";
        //用户关注作者key----作者id-用户id
        String uFollowKey = dto.getAuthorId() + "_" + userId;
        String followers = (String) cacheService.hGet(followKey, "follow");
        if (followers == null){
            //初始化作者关注
            cacheService.hPut(followKey, "follow", "0");
        }

        String uFollow = (String) cacheService.hGet(uFollowKey, "follow");
        if (uFollow == null){
            //初始化为未关注  --0未关注，1关注
            cacheService.hPut(uFollowKey, "follow", "0");
        }
        uFollow = (String) cacheService.hGet(uFollowKey, "follow");
        //判断用户操作
        if (dto.getOperation() == 0 && "0".equals(uFollow)){
            //关注作者
            log.info("关注作者");
            cacheService.hIncrBy(followKey, "follow", 1);
            cacheService.hPut(uFollowKey, "follow", "1");
        } else if (dto.getOperation() == 1 && "1".equals(uFollow)){
            //取消关注
            log.info("取消关注");
            cacheService.hIncrBy(followKey, "follow", -1);
            cacheService.hPut(uFollowKey, "follow", "0");
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        return ResponseResult.okResult(null);
    }
}
